import { defineStore } from 'pinia'
import {getUserMenuListApi} from '@/views/system/menu/api'
import {toRaw} from 'vue'
import {
  generateMenuTree,
  fullScreenRoute,
  menuTreeToRouter,
  handleRouter,
  getAuthorityButton,
  getKeepAliveRouter,
  addRoute,
  handlePath
} from '@/utils/handleMenu'


export interface MenuStore {
  isCollapse:boolean
  menuList: any[]
  authButton:string[]
  keepAliveRouter:string[]
}

export const menuStore = defineStore({
  id: 'menu',
  state: ():MenuStore => {
    return {
      isCollapse: false,
      menuList: [],
      authButton:[],
      keepAliveRouter:[]
    }
  },
  actions: {
    setCollapse() {
      this.isCollapse = !this.isCollapse
    },
    async setMenuList() {
      //获取平级菜单列表
      const { data } = await getUserMenuListApi()
      //菜单排序
      const sortMenu = data.sort((x,y) => x.sort - y.sort)
      //过滤按钮权限
      this.authButton = getAuthorityButton(sortMenu)
      //获取缓存菜单名称
      this.keepAliveRouter = getKeepAliveRouter(sortMenu)
      //平级菜单转菜单树
      const menuTree = generateMenuTree(sortMenu)
      //菜单树转路由树
      this.menuList = menuTreeToRouter(menuTree)
      //过滤全屏菜单,权限按钮,外链
      const routerList = handleRouter(toRaw(this.menuList))
      //菜单处理成路由需要的path
      const resultRouters = handlePath(routerList)
      //获取全屏路由
      const fullscreenRouter = handlePath(fullScreenRoute(toRaw(this.menuList)))
      //动态加一级路由(全屏)
      addRoute(fullscreenRouter)
      //动态加二级路由
      addRoute('AppMain',resultRouters)
    },
  },
})
